package at.jaki.ubb.crawling.demo.ui;

import java.awt.BorderLayout;
import java.util.Collection;

import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;

import at.jaki.ubb.crawling.demo.core.Listener;
import at.jaki.ubb.crawling.demo.model.StarData;

public final class UiManager {

	public static final String ACTION_GET_STAR = "getStar";
	public static final String ACTION_SHOW_STAR = "showStar";

	private static final String TITLE = "Exo planet finder - Crawling Engine Sample implementation";

	private static UiManager instance;

	public static UiManager getInstance() {
		if (instance == null) {
			instance = new UiManager();
		}
		return instance;
	}

	@Override
	protected Object clone() throws CloneNotSupportedException {
		throw new CloneNotSupportedException();
	}

	private JFrame frame;
	private JPanel mainPanel;
	private JPanel north;
	private JPanel center;
	private Listener listener;
	private JTextField searchFor;

	private JComboBox jcb;

	private UiManager() {
	}

	public void init(Listener listener) {
		this.listener = listener;
		initUi();
		initCenter();
	}

	private void initUi() {
		frame = new JFrame(TITLE);
		frame.addWindowListener(listener);
		mainPanel = new JPanel(new BorderLayout());
		north = new JPanel();
		center = new JPanel(new BorderLayout());
		mainPanel.add(north, BorderLayout.NORTH);
		mainPanel.add(center, BorderLayout.CENTER);
		frame.getContentPane().add(mainPanel);

		initNorth();

		frame.setSize(400, 200);
		frame.setVisible(true);

	}

	private void initNorth() {
		north.setVisible(false);
		searchFor = new JTextField(20);
		JLabel label = new JLabel("Star id");
		JPanel p = new JPanel();
		JButton getStar = new JButton();
		getStar.setText("get star");
		getStar.setActionCommand(ACTION_GET_STAR);
		getStar.addActionListener(listener);
		p.add(label);
		p.add(searchFor);
		p.add(getStar);
		north.add(p);
		north.setVisible(true);
	}

	private void initCenter() {
		center.setVisible(false);
		JPanel p = new JPanel();
		jcb = new JComboBox();
		p.add(jcb);
		JButton showStar = new JButton();
		showStar.addActionListener(listener);
		showStar.setActionCommand(ACTION_SHOW_STAR);
		showStar.setText("show star");
		p.add(showStar);
		center.add(p);
		center.setVisible(true);
	}

	public String getSearchText() {
		return searchFor.getText();
	}

	public void addStars(Collection<String> list) {
		for (String s : list) {
			addStar(s);
		}
	}
	
	public void addStar(String s){
		jcb.addItem(s);
	}

	public String getSelected() {
		return jcb.getSelectedItem().toString();
	}

	public void showStar(StarData byId) {
		JFrame jf = new JFrame(byId.getId());
		jf.setContentPane(ChartUtils.generateChart(byId));
		jf.pack();
		jf.setVisible(true);
	}
}
